/**
 * 基于 braft-editor
 */

import React, {Component} from 'react'
import PropTypes from 'prop-types'
// 引入编辑器以及编辑器样式
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/braft.css'

class SbraftEditor extends Component {

  constructor (props) {
    super(props)
    this.editorInstance = null
  }

  // 预览
  preview = () => {
    if (window.previewWindow) {
      window.previewWindow.close()
    }
    window.previewWindow = window.open()
    window.previewWindow.document.write(this.buildPreviewHtml())
  }

  ipAndPort = () => {
    return 'http://127.0.0.1:9998'
  }

  uploadFn = (param) => {

    const serverURL = this.props.serverURL
    console.log(`---- ${serverURL}`)
    const xhr = new XMLHttpRequest()
    const fd = new FormData()
    const mediaLibrary = this.editorInstance.getMediaLibraryInstance()

    // libraryId可用于通过mediaLibrary示例来操作对应的媒体内容
    // console.log(param.libraryId)

    const successFn = (response) => {
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      param.success({
        // qiniu
        // url: 'http://' + xhr.responseText,
        // TODO springboot 页面无法加载本地资源
        url: this.ipAndPort() + JSON.parse(xhr.responseText).data,
        meta: {
          // id: 'xxx',
          // title: 'xxx',
          // alt: 'xxx',
          loop: false, // 指定音视频是否循环播放
          autoPlay: false, // 指定音视频是否自动播放
          controls: true, // 指定音视频是否显示控制栏
          // poster: 'https://www.baidu.com/img/bd_logo1.png?where=super', // 指定视频播放器的封面
        },
      })
    }

    const progressFn = (event) => {
      // 上传进度发生变化时调用param.progress
      param.progress(event.loaded / event.total * 100)
    }

    const errorFn = (response) => {
      // 上传发生错误时调用param.error
      param.error({
        msg: 'unable to upload.',
      })
    }

    xhr.upload.addEventListener("progress", progressFn, false)
    xhr.addEventListener("load", successFn, false)
    xhr.addEventListener("error", errorFn, false)
    xhr.addEventListener("abort", errorFn, false)

    fd.append('file', param.file)
    xhr.open('POST', serverURL, true)
    xhr.send(fd)

  }

  validateFn = (file) => {
    return file.size <= 1024 * 100
  }

  // 编辑器多媒体插入功能
  mediaProps = () => {
    return {
      uploadFn: (param) => this.uploadFn(param),
    }
  }

  buildPreviewHtml () {

    return `
      <!Doctype html>
      <html>
        <head>
          <title>文章预览</title>
          <style>
            html,body{ height: 100%; margin: 0; padding: 0; overflow: auto; background-color: #f1f2f3; }
            .container{ box-sizing: border-box; width: 1000px; max-width: 100%; min-height: 100%; margin: 0 auto; padding: 30px 20px; overflow: hidden; background-color: #fff; border-right: solid 1px #eee; border-left: solid 1px #eee; }
            .container img, .container audio, .container video{ max-width: 100%; height: auto; }
            .container p { white-space: pre-wrap; }
          </style>
        </head>
        <body>
            <div class="container">${this.props.editHtmlContent}</div>
        </body>
      </html>
    `

  }

  insertHTMLContent = () => {
    //this.editorInstance.insertHTML('<p><img src="https://cdn.dribbble.com/users/1224447/screenshots/4576582/800x600_1x.png" /></p><p>12312312312<a href="123123123">baidu.com</a></p><p>asdasdas<u><span style="text-decoration:line-through;"><strong>da<em><span style="font-size:32px;color:#fdda00;background-color:#07a9fe;">s</span>d</em>ad</strong>asdas</span></u>d</p>')
    this.editorInstance.insertHTML('<p><span style="color:#ff0000;">Hello World!</span></p>')
  }

  /**
   * editor 内容变化检测，刷新内部 state
   */
  onHTMLChange = (htmlContent) => {
    this.props.onHTMLChange(htmlContent)
  }

  render () {
    const extendControls = [
      {
        type: 'split',
      },
      // {
      //   type: 'button',
      //   className: 'preview-button',
      //   text: <span>测试</span>,
      //   onClick:()=>{
      //     this.editorInstance.insertMedias([{
      //       type: 'VIDEO',
      //       url: 'http://www.baidu.com',
      //       meta: {
      //         poster: 'https://t11.baidu.com/it/u=4159415578,2157591270&fm=173&app=25&f=JPEG?w=500&h=333&s=8A206184576332ACCEB834820300A093',
      //       },
      //     }])
      //   },
      // },
      {
        type: 'button',
        className: 'preview-button',
        text: <span>预览</span>,
        onClick: this.preview,
      },
      // {
      //   type: 'button',
      //   className: 'preview-button',
      //   text: <span>增加颜色</span>,
      //   onClick: () => {
      //     this.editorInstance.addTempColors(['#0099ae', '#0049ae', '#4099ae', '#00c9fe'])
      //   },
      // },
      // {
      //   type: 'dropdown',
      //   width: 80,
      //   disabled: false,
      //   arrowActive: false,
      //   text: <span>下拉框</span>,
      //   html: '<span style="color:#0f0;">下拉框</span>',
      //   autoHide: false,
      //   ref: instance => window.customDropDown = instance,
      //   component: <h1 style={{width: 200, color: '#ffffff', padding: 10, margin: 0}}>Hello World!</h1>,
      // },
      // {
      //   type: 'modal',
      //   html: '<span style="color:#f00;">弹出框</span>',
      //   text: '弹出框',
      //   className: 'modal-button',
      //   modal: {
      //     id: 'test-modal',
      //     title: '这是一个弹出框',
      //     showClose: true,
      //     showCancel: true,
      //     showConfirm: true,
      //     confirmable: true,
      //     onCreate: modal => this.myModal = modal,
      //     children: (
      //       <div style={{width: 480, height: 320, padding: 30}}>
      //         <span>Hello World!</span>
      //       </div>
      //     ),
      //   },
      // },
      // {
      //   type: 'button',
      //   text: <span>添加自定义组件</span>,
      //   onClick: () => {
      //     this.editorInstance.insertMedias([{
      //       type: 'HELLO',
      //       name: 'BalBla',
      //     }])
      //   },
      // },
    ]

    return (
      <div>
        <div className="demo" id="demo">
          <BraftEditor
            initialContent={this.props.editHtmlContent}
            forceNewLine={true}
            // onHTMLChange={htmlContent => this.setState({ htmlContent })}
            onHTMLChange={htmlContent => this.onHTMLChange(htmlContent)}
            contentFormat='html'
            ref={instance => this.editorInstance = instance}
            extendControls={extendControls}
            // extendAtomics={extendAtomics}
            // media={
            //   uploadFn: (param) => this.uploadFn(param)
            // }
            media={this.mediaProps()}
          />
        </div>
        {/*<div><a href="javascript:void(0);" onClick={this.insertHTMLContent}>插入HTML片段</a></div>*/}
      </div>
    )
  }

}

SbraftEditor.propTypes = {}

export default SbraftEditor
